package org.project.controller2;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.ibatis.annotations.Param;
import org.project.dao.user.PayData;
import org.project.pojo.Message;
import org.project.pojo.Order;
import org.project.pojo.State2;
import org.project.service.user.ImgsService;
import org.project.service.user.Order1Service;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import net.sf.json.JSONObject;
import wxpay.app.util.ConstantUtil;
import wxpay.web.services.XMLUtil;


@Controller
@RequestMapping("/paycontroller")
public class Paycontroller {
	
	@Resource
	private ImgsService imgsService;
	
	@Resource
	private Order1Service order1Service;
	
	
	@RequestMapping("/getWeiXinPayData")
	@ResponseBody
	public PayData getWeiXinPayData(@Param("orderid")String orderid,@Param("openid")String openid){
		HttpServletRequest req = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		 Order order=order1Service.selectorder1(orderid);
		 String prepayPrice=order.getPrepayPrice();
		PayData payData=new PayData();
		payData.setPayDataObj(WeiXinPayGeyMap.doWeixinPay(prepayPrice, orderid, openid, req));
		
		return payData;
	}
	
	/**
	 * @方法名:微信支付回调
	 * @参数:
	 * @输出:
	 * @备注:
	 * @时间: 2017年11月8 1:35:45
	 * @修改:
	 */
	@SuppressWarnings({ "unchecked", "unused" })
	@RequestMapping("/weixinCallbacks")
	@ResponseBody
	public Object weixinCallback() {
		State2 state2=new State2();
		System.out.println("in____________________________");
		try {
			String out_trade_no = "";// 订单编号
			String total_fee = "";// 总金额(单位：分)
			String openid = "";// 微信用户在商户appid下的唯一标识
			String appid = "";// 应用ID
			String mch_id = "";// 商户号
			String transaction_id = "";// 流水号

			
			HttpServletRequest req = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
			InputStream inStream = req.getInputStream();
            
			ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = inStream.read(buffer)) != -1) {
				outSteam.write(buffer, 0, len);
			}
			outSteam.close();
			inStream.close();
			String result = new String(outSteam.toByteArray(), "utf-8");
			Map<Object, Object> map = null;
			try {
				map = XMLUtil.doXMLParse(result);
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (map != null && map.size() > 0) {
				for (Object keyValue : map.keySet()) {
					if (keyValue.equals("out_trade_no")) {
						out_trade_no = (String) map.get(keyValue);// 订单编号
						continue;
					}
					if (keyValue.equals("total_fee")) {
						total_fee = (String) map.get(keyValue);// 总金额(单位：分)
						continue;
					}
					if (keyValue.equals("openid")) {
						openid = (String) map.get(keyValue);// 微信用户在商户appid下的唯一标识
						continue;
					}
					if (keyValue.equals("appid")) {
						appid = (String) map.get(keyValue);
						continue;
					}
					if (keyValue.equals("mch_id")) {
						mch_id = (String) map.get(keyValue);
						continue;
					}
					if (keyValue.equals("transaction_id")) {
						transaction_id = (String) map.get(keyValue);
						continue;
					}
				}
			}
			// 验证
			if (appid.equals(ConstantUtil.APP_ID) && mch_id.equals(ConstantUtil.PARTNER)) {
				if (out_trade_no != null && !out_trade_no.equals("")) {
					
					//boolean flag = OrderController.buyCourseAddData(out_trade_no);
					String orderid=out_trade_no;
					int i=imgsService.payorder(orderid);
					
					JSONObject obj = new JSONObject();
					obj.put("obm", out_trade_no);
					
					
					
										
					if (i>0) {
						
						System.out.println("wx通知订单成功！！！！！！！！！！！！！");
						//state2.setReturn_code("SUCCESS");
					//	System.out.println("aaaaaaaa"+state2.getReturn_code());
						Message message=new Message();
						Order order=order1Service.selectyuewzf333(orderid); 
						message.setOrderid(orderid);
						
						message.setOrderTime(order.getOrderTime());
						message.setTelephone(order.getPhone());
						String orderTime=order.getOrderTime();
						
						
						//开始计算发送信息时间
						Date messageTime0=null;
						try {
							 messageTime0=timeChaange(orderTime);
						} catch (ParseException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH:mm");
						String messageTime = sim.format(messageTime0);
						message.setMessageTime(messageTime);
						
						order1Service.insertmessage(message);
						order1Service.deleteouttime(orderid);//删除过期数据
						return "success";
					}
				} else {
				    //System.out.println("wx通知订单为空@@@@@@@@@@@@@@@@@@@@@@");
					//renderJson("fail");
				//	state2.setReturn_code("FAIL");
				//	System.out.println("fail1111111"+state2.getReturn_code());
                       return "fail";				
				}
			} else {
			/*	System.out.println("商户appid和商户号验证失败:");
				System.out.println("appid:" + appid);
				System.out.println("mch_id:" + mch_id);*/
				//renderJson("fail");
				//state2.setReturn_code("FAIL");
				//System.out.println("fail22222222"+state2.getReturn_code());
				  return "fail";		
			}
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		     return "success";
	}
	
	
	 //计算前两个小时
	 public static Date timeChaange (String timeStr) throws ParseException {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			Date time = sdf.parse(timeStr);
			Calendar cal = Calendar.getInstance();
			cal.setTime(time);
			cal.add(Calendar.HOUR_OF_DAY, -2);
			time = cal.getTime();
			return time;
		}
	
}
